require_relative 'src/env'

SECONDS_TO_WAIT = 60
TIMES_TO_TRY = 5

def check_pidfile(pidfile, tries)
  if File.exist?(pidfile)
    oldpid = File.read(pidfile).to_i
    # does that process exist?

    ps = `ps -p #{oldpid} -o pid,start,etime,args`

    exists = true
    begin
      Process.kill(0, oldpid) # signal is 0, meaning, no signal is sent, but error checking is still performed.
    rescue Errno::ESRCH # Invalid pid
      File.delete(pidfile)
      exists = false
    rescue ::Exception   # for example on EPERM (process exists but does not belong to us)
      exists = true
      raise
    end
    if tries <= 0
      raise StandardError.new("There can be only one #{pidfile} (#{oldpid}) on #{CDO.name} (#{rack_env}) \n#{ps}") if exists
    else
      puts "found a competing rake, waiting #{SECONDS_TO_WAIT}s"
      sleep(SECONDS_TO_WAIT)
      check_pidfile(pidfile, tries - 1)
    end
  end
end

def there_can_be_only_one(pidfile)
  check_pidfile(pidfile, TIMES_TO_TRY)
  File.open(pidfile, "w") { |f| f.puts $$ }
  at_exit { File.unlink(pidfile) }
end

there_can_be_only_one("#{File.basename(__FILE__)}.pid") unless ENV['PEGASUS_RAKE_RECURSIVE'].to_s.downcase == 'true'

if ENV['PEGASUS_RAKE_LOGGER'].to_s.downcase != 'true'
  $log = Logger.new STDOUT
  $log.level = Logger::INFO
end

require_relative 'src/database'

Dir.glob(pegasus_dir('rake/*.rake')) {|path| load path}

namespace :pegasus do
  task :setup_db => ['db:ensure_created', 'db:migrate', 'seed:migrate'] do
  end
end

task :help do
  puts 'build:help'
  puts 'db:help'
  puts 'i18n:help'
  puts 'seed:help'
  puts 'test'
end
